<?php

/**
 * this class provides functions for creating a request
 * @author		ungerboeck simon <su@militaerversand.at>
 *
 */
class ResponseInfo {
	private $data = null;
	
	/************************************************************************
	 *************************** PUBLIC FUNCTIONS ***************************
	************************************************************************/
	
	/**
	 * initializes the data array
	 */
	public function __construct(){
		$this->data = array('STATUS' => SUCCESS, 'FIELDS' => array(), 'MESSAGES' => array());
	}
	
	
	/**
	 * sets the status to failed
	 */
	public function failed(){
		$this->data['STATUS'] = FAILED;
	}
	
	
	/**
	 * returns true of the response successed
	 * @return		boolean
	 */
	public function success(){
		return $this->status == SUCCESS;
	}
	
	
	/**
	 * adds a field to data array
	 * @param 		mixed		 $field
	 */
	public function addField($field){
		$this->data['FIELDS'][] = $field;
	}
	
	
	/**
	 * adds a message to the data array
	 * @param 		string		 $message
	 */
	public function addMessage($message){
		$this->data['MESSAGES'][] = $message;
	}
	
	
	/**
	 * sets a new index to the data array
	 * @param 		string		 $index
	 * @param 		string		 $value
	 */
	public function __set($index, $value){
		$this->data[strtoupper($index)] = $value;
	}
	
	
	/**
	 * gets the value form the data array
	 * @param 		string		 $index
	 */
	public function __get($index){
		$index = strtoupper($index);
		if (array_key_exists($index, $this->data))
			return $this->data[$index];
	}
	
	
	/**
	 * creates the info
	 * @return 		string
	 */
	function create(){
		return json_encode($this->data);
	}
	
	
	/**
	 * creates the info
	 * @return 		string		
	 */
	public function __toString(){
		return $this->create();
	}
	
	
	/**
	 * add errors to the response array
	 * @param 		mixed		 $entity
	 * @param 		string		 $prefix
	 */
	public function addErrors($entity, $prefix) {
		$this->failed();
		$errors = $entity->errors()->getMessages();
		$this->failed();
		foreach ($errors as $fieldName => $messages) {
			foreach ($messages as $message) {
				$this->addMessage($message);
				$this->addField($prefix . strtoupper($fieldName));
			}
		}
	}
	
	
	/**
	 * clears the response array
	 */
	public function clear(){
		$this->data = array();
	}
	
	/************************************************************************
	 ************************** PRIVATE FUNCTIONS ***************************
	************************************************************************/
}